package com.daman.goods

import com.daman.db.{DbOps, DBToolkit}
import com.daman.{Respond, AppAction}
import xitrum.SkipCsrfCheck
import xitrum.annotation.{PUT, POST, GET, Swagger}

@GET("p/category")
@Swagger(
  Swagger.Note("get the list of category")
)
class Category extends  CategoryApi{
  def execute() {
    val offset = paramo[Int]("offset").getOrElse(0)
    val size = paramo[Int]("size").getOrElse(10)
    respondJson(Respond.success(CategoryOps.list(offset,size)))
  }
}

@PUT("p/category/:id<[0-9]+>")
class CategoryPut extends CategoryApi{
  def execute(){
    val id      = param[Int]("id")
    getPost((input:Map[String,String]) =>{
      val result = CategoryOps.updById(id,input)
      respondJson(Respond.success(result))
    })
  }
}

@POST("p/category")
class CategoryPost extends  CategoryApi{
  def execute() {
      getPost((data:Map[String,String]) =>{
        val result = CategoryOps.insert(data)
        respondJson(Respond.success(result.toString))
      })
  }
}


object CategoryOps extends DbOps{
  override def dbName: String = CategoryTable.tableName

  override  def insert(fields:Map[String,String]) = {
    val conn = DBToolkit.getConn()
    val safeFields = CategoryTable.created_at+","+CategoryTable.updated_at
    val safeValues = "NOW(),NOW()"
    val result = DBToolkit.insertReturnId(conn,dbName,fields,safeFields,safeValues)
    DBToolkit.closeConn(conn)
    result
  }

  override def updById(id:Int,fields:Map[String,String]) = {
    val conn = DBToolkit.getConn()
    val safeFieldValues =  CategoryTable.updated_at +"= NOW()"
    val result = DBToolkit.update(conn,dbName,fields,Map(m_id->id.toString),safeFieldValues)
    DBToolkit.closeConn(conn)
    result
  }
}

@Swagger(
  Swagger.Resource("category", "Operations product(goods) category "),
  Swagger.Produces("application/json")
)
trait  CategoryApi extends  AppAction  with SkipCsrfCheck {
}

object CategoryTable {
  val tableName = "da_goods_category"
  val id = "id"
  val parent_id = "parent_id"
  val name = "name"
  val created_at = "created_at"
  val updated_at = "updated_at"
}